package com.qiudao.multipleDataSource.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * Description: 配置多数据源_ali
 * @author: gdc
 * @date: 2019/10/9
 * @version 1.0
 */
@Configuration
@MapperScan(basePackages = {"com.qiudao.multipleDataSource.mapper.ali"}, sqlSessionFactoryRef = "sqlSessionFactoryAli")
public class MybatisDbAliConfig {

    @Value("${mapper-locations.ali}")
    private String mapperLocation;

    /**
     * 注入数据源 bean
     */
    @Bean(name = "ali")
    @ConfigurationProperties(prefix = "spring.datasource.ali")
    public DataSource dataSourceAli() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 注入数据工厂 bean，需要添加指定的数据库
     * 注入的 SqlSessionFactory 需要一个设置 @Primary
     */
    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactoryAli(MybatisProperties mybatisProperties) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSourceAli());
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocation));
        // 由于出现过配置多数据源时，控制台Sql 日志无法打印，因此可通过在一个工厂类配置 MyBatisProperties 解决
        factoryBean.setConfiguration(mybatisProperties.getConfiguration());
        return factoryBean.getObject();
    }

    /**
     * 注入模板 bean ,需要添加指定的数据工厂
     */
    @Bean
    public SqlSessionTemplate sqlSessionTemplateAli(@Qualifier("sqlSessionFactoryAli") SqlSessionFactory sqlSessionFactoryAli) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryAli);
    }

    /**
     *
     * @return
     */
    @Bean
    public MybatisProperties mybatisProperties(){
        return new MybatisProperties();
    }
}
